/**
 * Module dependencies.
 */

var express = require('express'),
    routes = require('./routes'),
    logger = require('./config/log'),
    user = require('./routes/user'),
    test = require('./routes/test'),
    admin = require('./routes/admin'),
    http = require('http'),
    path = require('path'),
    ejs = require('ejs'),
    app = express();

var passport = require('passport'),
    GoogleStrategy = require('passport-google').Strategy;

// all environments
app.set('port', process.env.PORT || 3000);
app.set('views', path.join(__dirname, 'views'));
app.engine('.html', ejs.__express);
app.set('view engine', 'html');
app.use(express.favicon());
app.use(express.logger('dev'));
app.use(express.bodyParser());
app.use(express.json());
app.use(express.urlencoded());
app.use(express.methodOverride());
app.use(express.cookieParser())
app.use(express.session({
    secret: 'binwh',
    cookie: {
        maxAge: 60000
    }
}));
// Initialize Passport! Also use passport.session() middleware, to support
// persistent login sessions (recommended).
app.use(passport.initialize());
app.use(passport.session());
// logger add
logger.use(app);
// logger end
app.use(app.router);
app.use(express.static(path.join(__dirname, 'public')));
app.use(express.static(path.join(__dirname, 'bower_components')));

// development only
if ('development' == app.get('env')) {
    app.use(express.errorHandler());
}


// Passport session setup.
// To support persistent login sessions, Passport needs to be able to
// serialize users into and deserialize users out of the session. Typically,
// this will be as simple as storing the user ID when serializing, and finding
// the user by ID when deserializing. However, since this example does not
// have a database of user records, the complete Google profile is serialized
// and deserialized.
passport.serializeUser(function(user, done) {
    //保存user对象
    done(null, user); //可以通过数据库方式操作
});

passport.deserializeUser(function(obj, done) {
    //删除user对象
    done(null, obj); //可以通过数据库方式操作
});


// Use the GoogleStrategy within Passport.
// Strategies in passport require a `validate` function, which accept
// credentials (in this case, an OpenID identifier and profile), and invoke a
// callback with a user object.
var domain = require('./config/domain.json');
passport.use(new GoogleStrategy({
        returnURL: 'http://' + domain.domain + '/auth/google/return',
        realm: 'http://' + domain.domain
    },
    function(identifier, profile, done) {
        // asynchronous verification, for effect...
        process.nextTick(function() {

            // To keep the example simple, the user's Google profile is returned to
            // represent the logged-in user. In a typical application, you would want
            // to associate the Google account with a user record in your database,
            // and return that user instead.
            profile.identifier = identifier;
            return done(null, profile);
        });
    }
));


app.get('/', routes.index);
app.get('/users', user.list);
app.get('/test', test.blog);
app.get('/search', routes.search);

app.get('/admin', admin.ensureAuthenticated, admin.admin);
app.get('/admin/bm', admin.ensureAuthenticated, admin.adminBookMark);
app.get('/admin/bmxml', admin.ensureAuthenticated, admin.adminBookMarkXml);
app.post('/admin/bm/plus', admin.ensureAuthenticated, admin.admin);
app.post('/admin/bm/update', admin.ensureAuthenticated, admin.doBookmarkUpdate);
app.get('/login', admin.login);
app.get('/logout', admin.logout);
// GET /auth/google
// Use passport.authenticate() as route middleware to authenticate the
// request. The first step in Google authentication will involve redirecting
// the user to google.com. After authenticating, Google will redirect the
// user back to this application at /auth/google/return
app.get('/auth/google',
    passport.authenticate('google', {
        successRedirect: '/admin',
        failureRedirect: '/login'
    })
);
// GET /auth/google/return
// Use passport.authenticate() as route middleware to authenticate the
// request. If authentication fails, the user will be redirected back to the
// login page. Otherwise, the primary route function function will be called,
// which, in this example, will redirect the user to the home page.
app.get('/auth/google/return',
    passport.authenticate('google', {
        successRedirect: '/admin',
        failureRedirect: '/login'
    })
);

http.createServer(app).listen(app.get('port'), function() {
    //console.log('Express server listening on port ' + app.get('port'));
    logger.logger('app').info('Express server listening on port ' + app.get('port'));
});